package com.fancy.learncenter.common;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.SeekBar;
import android.widget.TextView;

import com.fancy.learncenter.utils.DataUtil;
import com.fancy.learncenter.utils.LogUtil;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class Player implements MediaPlayer.OnBufferingUpdateListener,
        MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {
    public MediaPlayer mediaPlayer;
    private SeekBar skbProgress;
    private Timer mTimer = new Timer();

    TextView startTime;
    TextView endTime;


    public Player() {
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnBufferingUpdateListener(this);
            mediaPlayer.setOnPreparedListener(this);
        } catch (Exception e) {
            Log.e("mediaPlayer", "error", e);
        }

        mTimer.schedule(mTimerTask, 0, 1000);
    }

    public Player(SeekBar skbProgress) {
        this.skbProgress = skbProgress;
        this.skbProgress.setOnSeekBarChangeListener(new SeekBarChangeEvent());
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnBufferingUpdateListener(this);
            mediaPlayer.setOnPreparedListener(this);
        } catch (Exception e) {
            Log.e("mediaPlayer", "error", e);
        }

        mTimer.schedule(mTimerTask, 0, 1000);
    }


    public Player(SeekBar skbProgress, TextView startTime, TextView endTime) {
        this.skbProgress = skbProgress;
        this.skbProgress.setOnSeekBarChangeListener(new SeekBarChangeEvent());
        this.startTime = startTime;
        this.endTime = endTime;

        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnBufferingUpdateListener(this);
            mediaPlayer.setOnPreparedListener(this);
            mediaPlayer.setOnCompletionListener(this);
            mediaPlayer.setOnErrorListener(this);
        } catch (Exception e) {
            Log.e("mediaPlayer", "error", e);
        }

        mTimer.schedule(mTimerTask, 0, 1000);
    }


    /*******************************************************
     * 通过定时器和Handler来更新进度条
     ******************************************************/
    TimerTask mTimerTask = new TimerTask() {
        @Override
        public void run() {
            if (mediaPlayer == null)
                return;
            if (mediaPlayer.isPlaying() && skbProgress != null && skbProgress.isPressed() == false) {
                handleProgress.sendEmptyMessage(0);
            }
        }
    };

    Handler handleProgress = new Handler() {
        public void handleMessage(Message msg) {

            int position = mediaPlayer.getCurrentPosition();
            int duration = mediaPlayer.getDuration();

            if (startTime != null) {
                String playTime = formatPlayTime(Long.valueOf(position));
                startTime.setText(playTime);
            }

            if (duration > 0) {

                if (skbProgress != null) {
                    long pos = skbProgress.getMax() * position / duration;
                    skbProgress.setProgress((int) pos);
                }

            }
        }
    };
    //*****************************************************

    public void play() {
        mediaPlayer.start();
    }

    public void playUrl(String videoUrl) {
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(videoUrl);
            mediaPlayer.prepareAsync();//prepare之后自动播放
//            mediaPlayer.stop();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    public void pause() {

        if (mediaPlayer != null) {
            mediaPlayer.pause();
        }

    }

    public void stop() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    public void release() {
        if (mediaPlayer != null) {
            mediaPlayer.pause();
        }
    }

    @Override
    /**
     * 通过onPrepared播放
     */
    public void onPrepared(MediaPlayer arg0) {
//        arg0.start();
        Log.e("mediaPlayer", "onPrepared");
        String duration = formatPlayTime((long) arg0.getDuration());

        if (endTime != null) {
            endTime.setText(duration);
        }


    }

    @Override
    public void onCompletion(MediaPlayer arg0) {
        Log.e("mediaPlayer", "onCompletion");
        playerStatus.playEnd();

        LogUtil.MyLog("playEnd", "========onCompletion===");
    }

    @Override
    public void onBufferingUpdate(MediaPlayer arg0, int bufferingProgress) {

        if (skbProgress != null) {
            skbProgress.setSecondaryProgress(bufferingProgress);
        }

//        int currentProgress = skbProgress.getMax() * mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration();
//        Log.e(currentProgress + "% play", bufferingProgress + "% buffer");
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        playerStatus.playEnd();
        return false;
    }


    class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {
        int pro;


        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//            if (!tvAudioTotalTime.getText().equals("00:00")) {
//
//                String runTime = DataUtil.formatPlayTime(Long.valueOf(pro));
////                tvAudioRunTime.setText(runTime);
//            }
            LogUtil.MyLog("onProgressChanged", "=========onProgressChanged=======" + pro);
            int position = mediaPlayer.getDuration();
            pro = progress * position / seekBar.getMax();
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mediaPlayer.seekTo(pro);
        }
    }

    private String formatPlayTime(Long time) {
        DateFormat formatter = new SimpleDateFormat("mm:ss");
        return formatter.format(new Date(time));
    }

    private PlayerStatus playerStatus;


    public void setPlayerStatus(PlayerStatus playerStatus) {
        this.playerStatus = playerStatus;
    }

    public interface PlayerStatus {
        void playStart();

        void playEnd();
    }
}